<?php

namespace App\Http\Controllers;

use App\Models\BindingRecord;
use App\Models\ChatRecords;
use App\Models\User;
use App\Models\UserChatGroup;
use App\Models\UserChatGroupUser;
use Illuminate\Http\Request;

//用户控制器
class UserController extends BaseController
{

    //用户/群组
    public function list(Request $request)
    {
        $type = $request->input('type', 'user');//user=检索用户,group=检索群组
        $keyword = $request->input('keyword', '');//用户/群组名 / 用户手机号
        $user_id = $request->input('user_id', '');//我用户id;
        if ($type == 'user') {
            //查用户
            $data = User::where('id', '!=', $user_id)
                ->where('nickname', 'like', "%{$keyword}%")
                ->orWhere('mobile', 'like', "%{$keyword}%")
                ->orderBy('id','desc')
                ->select('id', 'nickname', 'avatar')
                ->simplePaginate(7);
        } else {
            //查群组
            $data = UserChatGroup::where('name', 'like', "%{$keyword}%")->orderBy('sort','desc')->simplePaginate(7);
            foreach($data as $v){
                $v['nickname'] = $v['name'];
                $v['avatar'] = '/img/default_user.jpg';//OBS默认头像
                //获取群组中的最后一条聊天记录
                $record =  ChatRecords::query()->with(['binding_record'=>function($query){
                    $query->with(['user'=>function($query){
                        $query->select(['id','username','nickname']);
                    }]);
                }])->where(['group_id'=>$v['id']])->latest()->first();
                if($record){
                    $v['record'] = $record;
                    $v['unread_num'] = UserChatGroupUser::where('chat_group_id',$record['group_id'])
                        ->where('user_id',$user_id)
                        ->value('unread_num') ? :0;//获取未读消息数量
                }else{
                    $v['record'] = '';
                    $v['unread_num'] = 0;
                }
            }
        }
        //获取聊天记录列表

        return view('web.user.list', compact('data', 'user_id','keyword','type'));
    }

    //加载创建聊天群组页面
    public function addchatGroupForm(Request $request)
    {
        $user_id = $request->input('user_id');
        return view('web.user.add_chat_group',compact('user_id'));
    }

    //创建聊天群组
    public function addchatGroup(Request $request)
    {
        $user_id = $request->input('user_id');
        $name = $request->input('name');
        $count = UserChatGroup::where('user_id',$user_id)->count();
        if ($count >= 3){
            return redirect()->back()->with('error', '创建群数量已经达到上限(3个)');
        }

        UserChatGroup::create([
            'user_id'=>$user_id,
            'pic'=>'/img/default_user.jpg',
            'name'=>$name,
        ]);

        return redirect()->route('user.list',['type'=>'group','user_id'=>$user_id])->with('success', '操作成功');
    }

    //获取用户信息
    public function getUser(Request $request){
        $user_id = $request->input('user_id');
        $data = User::where('id',$user_id)->select('id','nickname','avatar')->first();

        $res = [
          'code'=>200,
          'user'=>[
              'nickname'=>'',
              'avatar'=>'/img/default_user.jpg',
          ]
        ];

        if (!$data){
            $res['code'] = 500;
            return $res;
        }
        $res['user']['nickname'] = $data['nickname'];
        $res['user']['avatar'] = $data['avatar'];
        return $res;
    }

    //获取聊天记录里列表
    public function getChatRecordsList(Request  $request){
        $bind_id = $request->input('bind_id');
        //查询聊天记录得到给我发消息的人
        $data = ChatRecords::where('addressee_id', $bind_id)
            ->groupBy('sender_id')
            ->selectRaw('MAX(id) as c_id')
            ->get();

        $sender_id = [];
        foreach ($data as $v) {
            //查找来聊天记录
            $chat_records = ChatRecords::where('id', $v['c_id'])->value('sender_id');
            if($chat_records){
                $sender_id[] = $chat_records;
            }
        }
        //找到绑定关系,获取用户信息
        $binding_record = BindingRecord::whereIn('id',$sender_id)->with(['user'])->get();

        $res_data = [];
        foreach ($binding_record as $v){
            //有用户信息的进数组,没用户信息的就是脏数据
            if ($v['user']['nickname'] ?? false){
                $res_data[] = [
                    'friend_id'=>$v['user_id'],//好友user_id
                    'nickname'=>$v['user']['nickname'] ?? '',//昵称
                    'avatar'=>env('OBSURL') . $v['user']['avatar'],//头像
                ];
            }
        }

        $res = [
            'code' => 200,
            'msg' => 'success',
            'data' => $res_data,
        ];
        return $res;
    }

    //获取指定用户聊天记录
    public function getChatRecordsShow(Request $request){
        $user_id = $request->input('user_id');//user表id
        $friend_id = $request->input('friend_id');//user表id

        //换成绑定id
        $user_bind_id = BindingRecord::where('user_id',$user_id)->value('id');
        $friend_bind_id = BindingRecord::where('user_id',$friend_id)->value('id');

        //获取聊天记录
        $chat_records = ChatRecords::where([
            ['sender_id',$user_bind_id],
            ['addressee_id',$friend_bind_id]
        ])
            ->orWhere([
                ['sender_id',$friend_bind_id],
                ['addressee_id',$user_bind_id]
            ])
            ->orderBy('id','desc')
            ->limit(30)
        ->get();
        $data = $chat_records->toArray();
        usort($data, function($a, $b) {
            return $a['id'] - $b['id'];
        });
        foreach($data as &$v){
            $v['created_at'] =  $this->tranTime(strtotime($v['created_at']));
        }
        $res = [
            'code'=>200,
            'msg'=>'success',
            'data'=>$data
        ];
        return $res;
    }
}
